# @Author   :hcs
# @File     :7-re的高级用法.py
# @Time     :2025/2/28 上午11:43

import re

# search(只能搜第一个）
# 需求：匹配出文章阅读的次数

ret = re.search(r"\d+", "阅读次数为9999,点赞数888，收藏666")
print(ret.group())

print('-' * 50)


def find_second_match(pattern, text):
    matches = re.finditer(pattern, text)
    try:
        next(matches)  # 跳过第一个匹配项
        second_match = next(matches)  # 获取第二个匹配项
        return second_match.group()
    except StopIteration:
        return None


#  findall  直接返回一个列表
# 需求：统计出python、c、c++相应文章阅读的次数
ret = re.findall(r"\d+", "python = 9999, c = 7890, c++ = 12345")
print(ret)

print('-' * 50)

#  sub 将匹配到的数据进行替换
# 需求：将匹配到的阅读次数加1
ret = re.sub(r"\d+", '998', "python = 997")
print(ret)

print('-' * 50)


def add(temp):
    strNum = temp.group()
    num = int(strNum) + 1
    return str(num)


ret = re.sub(r"\d+", add, "python = 997")
print(ret)
ret = re.sub(r"\d+", add, "python = 99")
print(ret)